﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using NewLife.Common;
using NewLife.Log;
using SmartIot.Models.SolarTerms;
using XCode;

namespace SmartIot.MicroTools.SolarTerms
{
    class Program
    {
        static void Main(string[] args)
        {
            XTrace.UseConsole();
            //注册编码规则
            System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);

            var dir = AppDomain.CurrentDomain.BaseDirectory;

            var dic = Test1(dir);
            Test2(dir, dic);
            Test3(dir);
            Test4();
            Test5(dir);
            Test6();
            Test7(dir);

            Console.WriteLine("Done !");
            Console.ReadLine();
        }

        private static void Test7(string dir)
        {
            var cat = AddDic("安徽省气象局", "链接地址");
            var path = Path.Combine(dir, "txt", "video", "ahnw.txt");
            var arr = File.ReadAllLines(path, Encoding.UTF8);
            foreach (var item in arr)
            {
                var infos = item.Split(new string[] { " ", "\t" }, StringSplitOptions.RemoveEmptyEntries);
                var term = Terms.Find(Terms._.Name, infos[1]);
                if (term != null)
                {
                    AddArticel(term.ID, cat.ID, term.Name, infos[2]);
                }
            }
        }

        private static void Test6()
        {
            var url = "http://www.cma.gov.cn/2011xzt/2018zt/essjq/{0}/";
            var cat = AddDic("中国气象局", "链接地址");
            IList<Terms> terms = Terms.FindAll();
            foreach (var item in terms)
            {
                AddArticel(item.ID, cat.ID, item.Name, url.F(PinYin.GetFirst(item.Name).ToLower()));
            }
        }

        private static void Test5(string dir)
        {
            IList<Terms> terms = Terms.FindAll();
            var categorys = TermsCategory.FindAll();
            var keys = categorys.Select(e => e.Key).ToArray();

            var path = Path.Combine(dir, "txt", "item");
            var itemDir = new DirectoryInfo(path);
            var files = itemDir.GetFiles();
            foreach (var file in files)
            {
                Console.WriteLine($"{file.Name}");
                var termName = file.Name.Replace(".txt", "");
                var term = terms.FirstOrDefault(e => e.Name.EqualIgnoreCase(termName));

                var str = ReadFile(file.FullName);
                var arr = str.Split(keys, StringSplitOptions.RemoveEmptyEntries);

                //处理基础信息
                var info = arr[0].Split(new string[] {  "(", ")", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
                term.En = info[1];
                term.TimeRange = info[4];
                term.SaveAsync();

                //三候
                var cat = categorys.FirstOrDefault(e => e.Key.EqualIgnoreCase("三候"));
                AddArticel(term.ID, cat.ID, "三候", arr[0]);

                //介绍
                var cat2 = categorys.FirstOrDefault(e => e.Key.EqualIgnoreCase("介绍"));
                AddArticel(term.ID, cat2.ID, "介绍", arr[1]);

                //由来
                var cat3 = categorys.FirstOrDefault(e => e.Key.EqualIgnoreCase("由来"));
                AddArticel(term.ID, cat3.ID, "由来", arr[2]);

                //习俗
                var cat4 = categorys.FirstOrDefault(e => e.Key.EqualIgnoreCase("习俗"));
                AddArticel(term.ID, cat4.ID, "习俗", arr[3]);

                //养生
                var cat5 = categorys.FirstOrDefault(e => e.Key.EqualIgnoreCase("养生"));
                AddArticel(term.ID, cat5.ID, "养生", arr[4]);

            }
        }

        static void AddArticel(int termId, int categoryId, string title, string content)
        {
            TermsArticle article = TermsArticle.Find(TermsArticle._.TermsID.Equal(termId) & TermsArticle._.CategoryID.Equal(categoryId));
            if (article == null)
            {
                article = new TermsArticle();
                article.TermsID = termId;
                article.CategoryID = categoryId;
                article.Title = title;
                article.Content = content;
                article.CreateTime = DateTime.Now;
                article.Save();
            }
        }

        private static void Test4()
        {
            AddDic("介绍", "");
            AddDic("三候", "");
            AddDic("由来", "");
            AddDic("习俗", "");
            AddDic("养生", "");
            AddDic("农业", "");
        }

        static TermsCategory AddDic(string key, string value)
        {
            var dic = TermsCategory.Find(TermsCategory._.Key, key);
            if (dic == null)
            {
                dic = new TermsCategory();
                dic.Key = key;
                dic.Value = value;
                dic.Save();
            }
            return dic;
        }

        private static void Test3(string dir)
        {
            var path = Path.Combine(dir, "txt", "img");
            var imgDir = new DirectoryInfo(path);
            var files = imgDir.GetFiles();
            foreach (var file in files)
            {
                Console.WriteLine($"{file.Name}");
                var fileName = file.Name.Replace(".jpg", "");
                var newName = PinYin.Get(fileName);
                // file.CopyTo(path + "\\" + newName + ".jpg", false);
                var url = $"img/SolarTerms/{newName}.jpg";
                var tag = "1";
                if (fileName.Length > 2)
                {
                    tag = fileName.Substring(2);
                }
                var term = Terms.Find(Terms._.Name.Equal(fileName.Substring(0, 2)));
                if (term == null)
                {

                }
                var album = TermsAlbum.Find(TermsAlbum._.TermsID.Equal(term.ID) & TermsAlbum._.Tag.Equal(tag));
                if (album == null)
                {
                    album = new TermsAlbum();
                    album.TermsID = term.ID;
                    album.Path = url;
                    album.Tag = tag;
                    album.Save();
                }
            }
        }

        private static void Test2(string dir, Dictionary<string, string> dic)
        {
            var path = Path.Combine(dir, "txt", "time");
            var timeDir = new DirectoryInfo(path);
            var files = timeDir.GetFiles();
            foreach (var file in files)
            {
                Console.WriteLine($"{file.Name}");
                var str = ReadFile(file.FullName);
                if (!str.IsNullOrWhiteSpace())
                {
                    var content = str.Split(dic.Keys.ToArray(), StringSplitOptions.RemoveEmptyEntries);

                    for (int i = 0; i < content.Length; i++)
                    {
                        string item = content[i];
                        var arr = item.Split(new string[] { "日", "月", " ", " ", ":", "：" }, StringSplitOptions.RemoveEmptyEntries);
                        var year = file.Name.Replace(".txt", "");
                        var month = arr[0];
                        var day = arr[1];
                        var hour = arr[2];
                        var min = arr[3];
                        var sec = arr[4];
                        var time = new DateTime(
                            Convert.ToInt32(year),
                            Convert.ToInt32(month),
                            Convert.ToInt32(day),
                            Convert.ToInt32(hour),
                            Convert.ToInt32(min),
                            Convert.ToInt32(sec)
                            );
                        if (time.Month == 1)
                        {
                            time = time.AddYears(1);
                        }
                        var name = dic.Keys.ElementAt(i);
                        Console.WriteLine($"{name}\t{time}");

                        var term = Terms.Find(Terms._.Name, name);
                        if (term == null)
                        {
                            SaveTerm(name, "");
                        }

                        TermsTime entity = TermsTime.Find(TermsTime._.TermsID.Equal(term.ID) & TermsTime._.Year.Equal(year));
                        if (entity == null)
                        {
                            entity = new TermsTime();
                            entity.TermsID = term.ID;
                            entity.Year = Convert.ToInt32(year);
                            entity.TermStartTime = time;
                            entity.Save();
                        }
                    }
                }
                Console.WriteLine("----------");
            }
        }

        private static Dictionary<string, string> Test1(string dir)
        {
            var dic = new Dictionary<string, string>();
            var file = Path.Combine(dir, "txt", "二十四节气说明.txt");
            var str = ReadFile(file);
            var arr = str.Split(new char[] { '\r', '\n', ' ' }, StringSplitOptions.RemoveEmptyEntries);
            if (arr.Any())
            {
                foreach (var item in arr)
                {
                    var arr2 = item.Split(new char[] { ':', ' ', '：' }, StringSplitOptions.RemoveEmptyEntries);
                    dic.Add(arr2[0], arr2[1]);
                }
            }
            dic.Keys.ToList().ForEach(key =>
            {
                var intro = dic[key];
                Console.WriteLine($"{key}:\t{intro}");

                var term = Terms.Find(Terms._.Name, key);
                if (term == null)
                {
                    SaveTerm(key, intro);
                }
            });
            return dic;
        }

        private static void SaveTerm(string key, string intro)
        {
            Terms term = new Terms();
            term.Name = key;
            term.Intro = intro;
            term.Save();
            XTrace.WriteLine($"初始化节气信息：{key}");
        }

        static string ReadFile(string file)
        {
            if (!File.Exists(file))
            {
                return null;
            }

            using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                using (StreamReader sr = new StreamReader(fs, Encoding.Default))
                {
                    var str = sr.ReadToEnd();
                    return str;
                }
            }
        }
    }
}
